﻿/**
 * Copyright (C) 2011 original author and authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NGuice.Inject.Internal.Util;

namespace NGuice.Inject.Spi
{
    //完成
    /// <summary>
    /// C#中没有泛型通配符，使用标记接口解决此问题
    /// </summary>
    public interface InjectionRequest : IElement
    {
        object Source
        {
            get;
        }

        Type Type
        {
            get;
        }

        object Instance
        {
            get;
        }

        /// <summary>
        /// 返回完成本次请求的将被注入的实例中的方法和域。
        /// </summary>
        /// <returns>
        /// 可能为空注入点集合。集合有特定的迭代顺序：超类的域--》子类域--》超类属性--》子类属性--》超类方法--》子类方法
        /// </returns>
        /// <exception cref="ConfigurationException">
        /// 如果有非正常的注入点在实例中则使用ConfigurationException#getPartialValue()的值加入集合
        /// </exception>
        ISet<InjectionPoint> GetInjectionPoints();


    }

    public sealed class InjectionRequest<T> : InjectionRequest
    {
        private readonly object source;
        //private readonly TypeLiteral<T> type;
        private readonly Type type;
        private readonly T instance;

        public InjectionRequest(object source, T instance)
        {
            this.source = Preconditions.CheckNotNull(source, "source");
            this.type = Preconditions.CheckNotNull(typeof(T), "type");
            this.instance = Preconditions.CheckNotNull(instance, "instance");
        }

        public object Source
        {
            get { return source; }
        }

        public Type Type
        {
            get { return type; }
        }

        public object Instance
        {
            get { return instance; }
        }

        public ISet<InjectionPoint> GetInjectionPoints()
        {
            return InjectionPoint.ForInstanceMethodsAndFields(instance.GetType());
        }

        public R AcceptVisitor<R>(IElementVisitor<R> visitor)
        {
            return visitor.Visit(this);
        }

        public void ApplyTo(IBinder binder)
        {
            binder.WithSource(Source).RequestInjection<T>(instance);
        }
    }
}
